package com.xhy.documents_collection.service.authority.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.entity.VO.AssignRoleVO;
import com.xhy.documents_collection.entity.VO.AuthorityVO;
import com.xhy.documents_collection.entity.PO.authority.Role;
import com.xhy.documents_collection.entity.PO.authority.RolePermission;
import com.xhy.documents_collection.entity.PO.authority.Tree;
import com.xhy.documents_collection.entity.PO.team.UserRole;
import com.xhy.documents_collection.mapper.authority.RoleMapper;
import com.xhy.documents_collection.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhy.documents_collection.service.authority.PermissionService;
import com.xhy.documents_collection.service.authority.RolePermissionService;
import com.xhy.documents_collection.service.authority.RoleService;
import com.xhy.documents_collection.service.authority.UserRoleService;
import com.xhy.documents_collection.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-11-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private PermissionService permissionService;


    @Override
    public List<Tree> tree() {
        List<Tree> trees = permissionService.list().stream().map(permission -> {

            Tree tree = new Tree();
            BeanUtils.copyProperties(permission, tree);
            tree.setTitle(permission.getName());
            tree.setSpread(true);
            return tree;
        }).collect(Collectors.toList());


        // 找到根节点
        List<Tree> parent = trees.stream().filter(tree -> tree.getPId().compareTo(0) == 0).collect(Collectors.toList());
        for (Tree item : parent) {
            item.setChildren(new ArrayList<Tree>());
            item.getChildren().add(findChildren(item,trees));
        }

        return parent;
    }

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    @Transactional
    public R removeRole(String id) {
        Role role = baseMapper.selectById(id);;
        Integer uid = UserHolder.get();
        try{

            // 删除角色权限中间表
            rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("r_id",id));
            // 删除角色表
            baseMapper.deleteById(id);
            // 删除用户角色表
            userRoleService.remove(new QueryWrapper<UserRole>().eq("r_id",id));
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("删除失败");
        }
        return R.ok().message("删除成功");
    }

    @Override
    @Transactional
    public R gavePermission(AuthorityVO authorityVO) {
        Integer uId = UserHolder.get();
        Role role = getById(authorityVO.getRid());
        try{
            rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("r_id",authorityVO.getRid()));
            List<RolePermission> list = new ArrayList<>();
            Integer rid = authorityVO.getRid();
            for (Integer pId : authorityVO.getPid()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRId(rid);
                rolePermission.setPId(pId);
                list.add(rolePermission);
            }
            long start = System.currentTimeMillis();
            rolePermissionService.saveBatch(list);
            long end = System.currentTimeMillis();
            System.out.println(end - start);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("分配权限失败");
        }
        return R.ok().message("分配权限成功");
    }
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public R gaveRole(AssignRoleVO assignRoleVO) {
        // 获取执行者id
        Integer adminId = UserHolder.get();
        // 获取被分配角色的用户信息
        Integer uId = assignRoleVO.getUId();
        String userName = userService.getById(uId).getName();
        try{
            userRoleService.remove(new QueryWrapper<UserRole>().eq("u_id",uId));
            List<UserRole> userRoles = new ArrayList<>();
            for (Integer id : assignRoleVO.getRId()) {
                UserRole userRole = new UserRole();
                userRole.setUId(uId);
                userRole.setRId(id);
                userRoles.add(userRole);
            }
            userRoleService.saveBatch(userRoles);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("分配角色失败");
        }
        return R.ok().message("分配角色成功");
    }

    private Tree findChildren(Tree datum, List<Tree> trees) {
        datum.setChildren(new ArrayList<Tree>());
        for (Tree tree : trees) {
            if (tree.getPId().compareTo(datum.getId()) == 0) {
                datum.getChildren().add(findChildren(tree,trees));
            }
        }
        return datum;
    }
}
